// ==UserScript==
// @name         gfycat resurrected
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Resurrect dead gfycat links all over Internet
// @author       boiledpotato23
// @homepage     https://notabug.org/boiledpotato23/gfycat-resurrected/
// @downloadURL  https://notabug.org/boiledpotato23/gfycat-resurrected/raw/master/gfycat-resurrected.user.js
// @updateURL    https://notabug.org/boiledpotato23/gfycat-resurrected/raw/master/gfycat-resurrected.user.js
// @match        *://*/*
// @icon         https://notabug.org/boiledpotato23/boiledpotato23/raw/cffea1f19170e2ca4836f5b508843e49607650f6/avatar.png
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const REGEXP = /^https:\/\/(?:[\w-]+\.)?gfycat\.com(?:\/.*)?$/;

    function setElementUrl(element, url) {
        if(element.tagName === "A") {
            element.href = url;
            return;
        }
        element.src = url;
    }

    function replaceGfycatLinks() {
        document.querySelectorAll('[href*="gfycat.com"], [src*="gfycat.com"]').forEach(element => {
            const originalUrl = element.tagName === "A" ? element.href : element.src;

            if(!originalUrl.match(REGEXP)) return;

            setElementUrl(element, "https://web.archive.org/web/1if_/" + originalUrl);
        });
    }

    window.addEventListener('load', replaceGfycatLinks);

    const observer = new MutationObserver(replaceGfycatLinks);
    observer.observe(document.body, { childList: true, subtree: true });
})();